<?php

namespace App\Jobs;

use App\Third\Gitee;
use App\Third\Ifff;
use App\User;
use App\Third\AccessToken;
use Carbon\Carbon;
use App\CustomMsgReply;
use App\CustomMsgReceive;


class SendCustomMessage extends Job
{
    // 0:表示接收, 1:表示回复, 2:表示系统下发消息到企业号
    private $type;
    private $fromUserName;
    private $msgType;
    private $msgId;
    private $createTime;
    private $content;
    private $picUrl;
    private $sendfrom;


    public function __construct($type,
                                $fromUserName,
                                $msgType,
                                $msgId,
                                $createTime,
                                $content,
                                $picUrl,
                                $sendfrom = '') {
        $this->type = $type;
        $this->fromUserName = $fromUserName;
        $this->msgType = $msgType;
        $this->msgId = $msgId;
        $this->createTime = $createTime;
        $this->content = $content;
        $this->picUrl = $picUrl;
        $this->sendfrom = $sendfrom;
    }

    public function handle() {
        if ($this->type == 0) {
            $this->receiveMessage();
        } elseif ($this->type = 1) {
            $this->replyMessage();
        }
    }

    private function replyMessage() {
        //        Log::info('reply');
        // 先排重
        $preReply =  CustomMsgReply::where('msgId', $this->msgId)->first();
        if ($preReply) {
            return;
        }

        $accessToken = new AccessToken($this->appid, $this->secret);
        $access_token = $accessToken->getAccessToken();
        if ($this->msgType == 'text') {
            // 先判断是不是回复图片的编号
            if (is_numeric($this->content)) {
                $reply = new CustomMsgReply;

                $reply->custommegreceive_id = $this->content;
                $reply->fromUserName = $this->fromUserName;
                $reply->msgType = $this->msgType;
                $reply->msgId = $this->msgId;
                $reply->createTime = $this->createTime;
                $reply->content = '';
                $reply->picUrl = $this->picUrl;

                $reply->save();
            } else {
                // 先判断
                $retContent = explode('@', $this->content, 2);

                // 查找接受消息内容
                $customerMsgReceive = CustomMsgReceive::find($retContent[0]);

                if ($customerMsgReceive) {
                    $option = [
                        'touser' => $customerMsgReceive->fromUserName,
                        'msgtype' => 'text',
                        'text' => [
                            'content' => $retContent[1]
                        ]
                    ];
                    $reply = new CustomMsgReply;

                    $reply->custommegreceive_id = $retContent[0];
                    $reply->fromUserName = $this->fromUserName;
                    $reply->msgType = $this->msgType;
                    $reply->msgId = $this->msgId;
                    $reply->createTime = $this->createTime;
                    $reply->content = $retContent[1];
                    $reply->picUrl = $this->picUrl;

                    $reply->save();

                    $this->sendRequest("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token", $option, "", "POST");
                    $options = [
                        'type' => 'text',
                        'text' => "[".$this->fromUserName."]回复[".$retContent[0]."]: ".$retContent[1],
                        'sendfrom' => $this->sendfrom
                    ];
                    $this->sendRequest("api.bamasoso.com/weixinqiyehao/xcxcustommsg", $options, "", "POST");

                    // $this->systemMessage($customerMsgReceive);
                }
            }
        } elseif ($this->msgType == 'image') {
            $img_content = file_get_contents($this->picUrl);
            $filepath = fopen(base_path('public/chat/images/temp.jpg'), "w+");
            fclose($filepath);

            $filepath = base_path('public/chat/images/temp.jpg');
            file_put_contents($filepath, $img_content);
            $img_option = array(
                'media' => new \CURLFile($filepath),
                'filename' => 'temp',
                'content-type' => '	image/jpeg',
                'filelength' => filesize($filepath)
            );

            $sendurl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$access_token&type=image";
            $result = $this->sendFileRequest($sendurl, $img_option);

            if ($result && $result->media_id) {

                // 查找接受消息内容
                $customerMsgReply = CustomMsgReply::where('content', '')
                    ->where('fromUserName', $this->fromUserName)
                    ->where('picUrl', '')
                    ->orderBy('updated_at', 'desc')
                    ->first();

                if ($customerMsgReply) {
                    $option = [
                        'touser' => $customerMsgReply->receive->fromUserName,
                        'msgtype' => 'image',
                        'image' => [
                            'media_id' => $result->media_id
                        ]
                    ];
                    $customerMsgReply->fromUserName = $this->fromUserName;
                    $customerMsgReply->msgType = $this->msgType;
                    $customerMsgReply->msgId = $this->msgId;
                    $customerMsgReply->createTime = $this->createTime;
                    $customerMsgReply->content = '';
                    $customerMsgReply->picUrl = $result->media_id;

                    $customerMsgReply->save();

                    $this->sendRequest("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token", $option, "", "POST");
                    $options = [
                        'type' => 'news',
                        'title' => "[".$this->fromUserName."]回复[".$customerMsgReply->custommegreceive_id."]图片:",
                        'description' => "[图片]这是一条用户反馈的图片消息,点开后可以看完整图片",
                        'url' => $this->picUrl,
                        'picurl' => $this->picUrl,
                        'sendfrom' => $this->sendfrom
                    ];
                    $this->sendRequest("api.bamasoso.com/weixinqiyehao/xcxcustommsg", $options, "", "POST");
                    // $this->systemMessage($customerMsgReply->receive);
                }
            }
        }
    }

    private function receiveMessage() {
        // 先排重
        $preReceive =  CustomMsgReceive::where('msgId', $this->msgId)->first();
        if ($preReceive) {
            return;
        }
        $gitee = new Gitee();
        // todo 需要做判断，如果之前有创建过，则作为评论，否则 create issue
        $pre_receive = CustomMsgReceive::where('fromUserName', $this->fromUserName)->first();

        $receive = new CustomMsgReceive;

        $receive->fromUserName = $this->fromUserName;
        $receive->msgType = $this->msgType;
        $receive->msgId = $this->msgId;
        $receive->createTime = $this->createTime;
        $receive->content = $this->content;
        $receive->picUrl = $this->picUrl;
        $receive->save();
        if ($receive) {
            // 获取用户资料,下发昵称
            $user = User::where('openid', $this->fromUserName)->first();
            $username_temp = $this->fromUserName;
            $gender = '';
            if ($user) {
                $gender = $user->gender==1?'男':'女';
                $username_temp = $user->nickname;
            }

            if ($this->msgType == 'text') {
                $send_content = $this->content;
            } else {
                $send_content = "![图]($this->picUrl)";
            }
            if ($pre_receive) {
                $receive->number = $pre_receive->number;
                $receive->save();
                // 创建评论
                $gitee->createComments($pre_receive->number, "> [$username_temp]: $send_content > \n\n![avatar]($user->avatarurl)");
            } else {
                $issue = $gitee->createIssue("[$receive->id][$username_temp][$gender]", "> ".$send_content." > \n\n![avatar]($user->avatarurl)");
                $receive->number = $issue->number;
                $receive->save();
            }

            // 下发 ifff 提醒
            $ifff = new Ifff();
            $ifff->send2ifff($username_temp, $send_content, $user->avatarurl);
        }
    }

    // 发起外部网络请求
    private function sendRequest($url, $option = array(), $header = array(), $type = 'POST') {
        $curl = curl_init (); // 启动一个CURL会话
        curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE ); // 对认证证书来源的检查
        curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE ); // 从证书中检查SSL加密算法是否存在
        curl_setopt ( $curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模拟用户使用的浏览器
        if(!empty($option)){
            $options = json_encode ( $option ,JSON_UNESCAPED_UNICODE);
            curl_setopt ( $curl, CURLOPT_POSTFIELDS, $options ); // Post提交的数据包
        }
        if(empty($header)){
            $header = array('Content-Type: application/json');
        }
        curl_setopt ( $curl, CURLOPT_TIMEOUT, 30 ); // 设置超时限制防止死循环
        curl_setopt ( $curl, CURLOPT_HTTPHEADER, $header ); // 设置HTTP头
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
        curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, $type );
        $result = curl_exec ( $curl ); // 执行操作
        $result = json_decode($result);
        curl_close ( $curl ); // 关闭CURL会话
        return $result;
    }

    // 发起外部网络请求 --- 上传文件
    private function sendFileRequest($url, $option) {
        $curl = curl_init (); // 启动一个CURL会话
        curl_setopt ( $curl, CURLOPT_URL, $url ); // 要访问的地址
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $option);
        curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 ); // 获取的信息以文件流的形式返回
        //        curl_setopt ( $curl, CURLOPT_CUSTOMREQUEST, 'PATCH' );
        $result = curl_exec ( $curl ); // 执行操作
        $result = json_decode($result);
        curl_close ( $curl ); // 关闭CURL会话
        return $result;
    }
}
